const cloud = require('wx-server-sdk')
cloud.init()

// 辅助函数：将日期格式化为 YYYY-MM-DD
function formatDate(date) {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

exports.main = async () => {
  const db = cloud.database()
  const wxContext = cloud.getWXContext()
  
  // 获取最近30天的打卡记录（使用本地时区）
  const now = new Date()
  const startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 29)
  
  const res = await db.collection('checkInRecords')
    .where({
      openid: wxContext.OPENID,
      createTime: db.command.gte(startDate)
    })
    .orderBy('createTime', 'asc')  // 改为正序排列
    .get()
    
  // 计算连续打卡天数
  let continuousDays = 0
  let lastDay = null
  const uniqueDays = new Set()
  
  // 1. 提取唯一日期（按本地时区）
  res.data.forEach(record => {
    const recordDate = new Date(record.createTime)
    // 使用本地时区转换
    const localDate = new Date(recordDate.getTime() + (8 * 60 * 60 * 1000))
    const dayKey = formatDate(localDate)
    uniqueDays.add(dayKey)
  })
  
  // 2. 将日期排序（从早到晚）
  const sortedDays = Array.from(uniqueDays).sort()
  
  // 3. 计算连续天数（从今天往前推）
  const today = formatDate(new Date(now.getTime() + (8 * 60 * 60 * 1000)))
  let currentStreak = 0
  let checkDate = new Date()
  
  // 检查最近连续打卡天数（最多30天）
  for (let i = 0; i < 30; i++) {
    const checkDateStr = formatDate(new Date(checkDate.getTime() + (8 * 60 * 60 * 1000)))
    
    if (sortedDays.includes(checkDateStr)) {
      currentStreak++
    } else {
      // 一旦发现中断，停止计数
      break
    }
    
    // 检查前一天
    checkDate.setDate(checkDate.getDate() - 1)
  }
  
  return {
    days: currentStreak,
    openid: wxContext.OPENID
  }
}